package eerbaar.shared.persist.internal.lib;

import eerbaar.area.IArea;
import eerbaar.game.GameFactory;
import eerbaar.game.IGame;
import eerbaar.level.ILevel;
import eerbaar.shared.exceptions.GameRuntimeException;
import eerbaar.shared.persist.IPersister;
import eerbaar.shared.persist.ISaver;
import eerbaar.shared.tree.INode;
import eerbaar.shared.tree.NodeCmdFactory;

public class GamePersister implements IPersister<IGame> {

    public static final String NAME = "game";

    private IGame target;

    public GamePersister() {
        //
    }

    public GamePersister(IGame wrapper) {
        this.target = wrapper;
    }

    public GamePersister(INode node) throws GameRuntimeException {
        load(node);
    }

    @Override
    public Class<IGame> getRegistertedInterface() {
        return IGame.class;
    }

    @Override
    public IPersister<?>[] getSavableChildren() {

        AreaPersister a = new AreaPersister(this.target.getArea());
        LevelPersister l = new LevelPersister(this.target.getLevel());
        return new IPersister<?>[] { a, l };
    }

    @Override
    public String getSavableName() {
        return NAME;
    }

    @Override
    public IGame getTarget() {
        return this.target;
    }

    @Override
    public boolean isAssignableFrom(ISaver<?> rsist) {
        return false;
    }

    @Override
    public IGame load(INode node) {
        assert (node != null);

        INode areaNode = NodeCmdFactory.findChild(node, AreaPersister.NAME);
        IArea area = new AreaPersister().load(areaNode);

        INode levelNode = NodeCmdFactory.findChild(node, LevelPersister.NAME);
        ILevel level = new LevelPersister().load(levelNode);

        return GameFactory.createGame(area, level);
    }

    @Override
    public void saveAttributes(INode node) {
        //
    }

    @Override
    public void setTarget(IGame obj) {
        this.target = obj;
    }

}
